
import store from '../store/index'
import router, { addRoute } from './index'
import { Message } from 'element-ui'


const filter = ["/login"]
router.beforeEach((to, from, next) => {
    if (store.state.userStore.token) {
        if (to.path === "/login") {
            Message.warning("你已经登录过了,请先退出登录")
            next("/")
        } else {
            if (to.meta.title) {
                document.title = to.meta.title
            } else {
                document.title = "Saas平台"
            }
            if (to.meta.menuTitle) {
                store.commit("setTitle", to.meta.menuTitle)
            }

            if (router.options.routes.length == 1) {
                addrouterSync(to, next)
            } else {
                next()
            }
        }
    } else {
        if (filter.includes(to.path)) {
            next()
        } else {
            next({ path: "/login", replace: true })
        }
    }

})

async function addrouterSync(to, next) {
    try {
        let route = await filterRouter(addRoute, store.state.userStore.role);
        store.commit("userStore/setAddRoute", route);
        route.forEach(v => {
            router.options.routes.push(v);
            router.addRoute(v);
        })
        let err = {
            path: "*",
            require: "/",
            component: () => import('@/views/HomeView.vue')
        }
        router.options.routes.push(err)
        router.addRoute(err);
        next({ ...to, replace: true })
    } catch (e) {
        console.log(e)
    }

}


function filterRouter(initRoute, storehouse) {

    function loop(initRoute, storehouse) {
        return initRoute.filter(v => {
            if (v.meta?.role?.includes(storehouse)) {
                if (v.children && v.children.length > 0) {
                    v.children = loop(v.children, storehouse)
                }
                return true
            }
        })
    }
    return Promise.resolve(loop(initRoute, storehouse))

}